//
//  PickNumRX9ListViewController.m
//  PlayBall
//
//  Created by Sun Fanglei on 13-5-28.
//
//

#import "JddPickNumRX9ListViewController.h"
#import "JddViewControllerManager.h"

@interface JddPickNumRX9ListViewController ()

@end

@implementation JddPickNumRX9ListViewController

@synthesize moneyLabel;
@synthesize titleLabel;
@synthesize countLabel;
@synthesize bgScrollView;
@synthesize buyBtn;
@synthesize endTime;
@synthesize numberArray;
@synthesize numberListTableView;
@synthesize issue;
@synthesize playMethodTemp;
@synthesize mutiTextfield;

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddPickNumRX9ListViewController);

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789\n"]invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    
    BOOL canChange = [string isEqualToString:filtered];
    
    if (!canChange) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"倍数只能输入数字"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil,nil ];
        [alert show];
        return NO;
    }
    if ([string length] + range.location>5) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"倍数不能大于99999"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil,nil ];
        [alert show];
        return NO;
    }
    
    if ([textField.text length]== 0) {
        if ([string isEqualToString:@"0"]) {
            return NO;
        }else {
            moneyLabel.text = [NSString stringWithFormat:@"%0.0f彩豆", count * [[textField.text stringByReplacingCharactersInRange:range withString:string] intValue] * 2];
            return YES;
        }
    }
    if (range.location>=5) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"倍数不能大于99999"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil,nil ];
        [alert show];
        return NO;
    }else {
        moneyLabel.text = [NSString stringWithFormat:@"%0.0f彩豆", count * [[textField.text stringByReplacingCharactersInRange:range withString:string] intValue] * 2];
        return YES;
    }
}

-(BOOL)textFieldShouldClear:(UITextField *)textField{
    return  YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapGesture:)];
    tapGestureRecognizer.delegate = self;
    [self.bgScrollView addGestureRecognizer:tapGestureRecognizer];
    [self.bgScrollView setContentOffset:CGPointMake(0,213) animated:YES];
    return YES;
}

- (IBAction)handleSingleTapGesture:(UITapGestureRecognizer*)sender{
    if ([mutiTextfield.text length]==0) {
        mutiTextfield.text = @"1";
    }
    [mutiTextfield resignFirstResponder];
    moneyLabel.text = [NSString stringWithFormat:@"%3.0f彩豆", count * [mutiTextfield.text floatValue] * 2];
    [self.bgScrollView removeGestureRecognizer:sender];
    [self.bgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return DELETE;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [numberArray count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JddsfcAndRx9ItemCell *cell = [JddsfcAndRx9ItemCell getInstanceView];
    JddSportNumber *ssqNumber = [numberArray objectAtIndex:indexPath.row];
    cell.HTeam.text = ssqNumber.Hteam;
    cell.VTeam.text = ssqNumber.Vteam;
    for (int b=0; b<[ssqNumber.teamArray count]; ++b) {
        NSString *sptemp = [ssqNumber.teamArray objectAtIndex:b];
        switch ([sptemp intValue]) {
            case 0:
                cell.sp3.image = [UIImage imageNamed:@"sport_select.png"];
                
                break;
            case 1:
                cell.sp2.image = [UIImage imageNamed:@"sport_select.png"];
                break;
            case 3:
                cell.sp.image = [UIImage imageNamed:@"sport_select.png"];
                break;
            default:
                break;
        }
    }
    cell.tag = indexPath.row;
    return cell;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if ([[alertView message] isEqualToString:@"您还没有登录，请先登录"]) {
        if (buttonIndex == 0) {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN
                                                                 fromController:self
                                                                     withObject:nil
                                                                    withObject2:nil];
        }
    } else if ([[alertView message] isEqualToString:@"确认购买？"]){
        if (buttonIndex==0) {
            [self sureToBuy];
        }
    }else if ([[alertView message] isEqualToString:@"确认清空列表？"]) {
        if (buttonIndex == 0) {
            playMethodTemp = [[NSMutableArray alloc] init];
            numberArray = [[NSMutableArray alloc] init];
            mutiTextfield.text = @"1";
            count = 0;
            self.titleLabel.text = @"共选择0场,截止时间:--------------";
            countLabel.text = [NSString stringWithFormat:@"%3.0f注", count];
            moneyLabel.text = [NSString stringWithFormat:@"%3.0f彩豆", count * [mutiTextfield.text floatValue] * 2];
            [numberListTableView reloadData];
        }
    }
}

-(void) sureToBuy{
    if ([self checkValue]) {
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    JddBuyLotteryOperation *operation2 = [[JddBuyLotteryOperation alloc] init];
    operation2.delegate = self;
    operation2.lotteryTypeId = [NSNumber numberWithInt:19];
    NSString *tste = [JddPickNumRX9ViewController sharedInstance].issueID;
    operation2.issueId = [NSNumber numberWithInt:[tste intValue]];
    operation2.multiple = [NSNumber numberWithInt:[mutiTextfield.text intValue]];
    operation2.moneyAmount = [NSNumber numberWithFloat:count * [mutiTextfield.text floatValue] * 2];
    operation2.lotteryNumber = [self lotteryNumberList];
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation2];
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (NSMutableArray*)lotteryNumberList{
    int playid = 1902;
    if(count > 1){
       if ([numberArray count] > 9) {
               playid = 1903;
       } else {
           playid = 1902;
       }
   }
    NSMutableArray *paramNumberArray = [[NSMutableArray alloc] init];
        int curTeamIndex = 0;
    NSMutableDictionary *numDic = [[NSMutableDictionary alloc] init];
    NSMutableString *lotteryNumberString = [NSMutableString string];
        for (int i=1; i<=14; i++) {
            JddSportNumber *ssqNumber = [numberArray objectAtIndex:curTeamIndex];
            if ([ssqNumber.code intValue] == i ) {
                for (int j=0; j<[ssqNumber.teamArray count]; ++j) {
                    NSString* team1 = [ssqNumber.teamArray objectAtIndex:j];
                    [lotteryNumberString appendString:team1];
                }
                if (curTeamIndex < [numberArray count]-1 ) {
                    curTeamIndex = curTeamIndex + 1;
                }
            }else{
                [lotteryNumberString appendString:@"#"];
            }
            if (i != 14) {
                [lotteryNumberString appendString:@","];
            }
        }
    [numDic setObject:[NSNumber numberWithInt:playid] forKey:@"playid"];
    [numDic setObject:lotteryNumberString forKey:@"number"];
    [paramNumberArray addObject:numDic];
    return paramNumberArray;
}

-(void)BuyLotteryOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        
        NSDictionary *ReDic = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
        if([[ReDic objectForKey:@"Code"] intValue] == 0)
        {
            // modify by rainy  修改投注使用接口不经过web
            NSString * fanganhao = [ReDic objectForKey:@"Data"];
            NSString *ls = ((JddPickNumRX9ViewController *)self.fromController).currentIssue.text;
            alert1 = [JddAlertView getInstanceView];
            alert1.lssueString = fanganhao;
            alert1.moneylable = moneyLabel.text;
            [alert1 alertBuyMessage:[NSString stringWithFormat:@"任选九%@期",ls]];
//            NSString*checkUrlString = [NSString stringWithFormat:@"%@?ck=%@",BASE_SERVER_IOS_BUY_LOTTERY_URL,[ReDic objectForKey:@"Data"]];
//            NSURL *checkUrl = [NSURL URLWithString:checkUrlString];
//            [[UIApplication sharedApplication] openURL:checkUrl];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"购彩失败"                                                  message:[ReDic objectForKey:@"Data"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil,nil ];
            [alert show];
        }
//        [JddCommonFunction updateBuyLotteryListWithLotteryId:LOTTERY_TYPE_ID_RX9];
        
    }
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if([touch.view isDescendantOfView:buyBtn]){
        return  NO;
    }
    return YES;
}

-(void)caculateMoneyAndCount{
    //caculate count and money
    count = 0;
    if([numberArray count] == 9){
        int mycout = 1;
        for (int i= 0; i<[numberArray count]; ++i) {
            JddSportNumber *ssqNumber = [numberArray objectAtIndex:i ];
            mycout = mycout*[ssqNumber.teamArray count];
        }
        count = mycout;
    }else{
        for (int i = 0; i<[numberArray count]; ++i) {
            JddSportNumber *ssqNumber = [numberArray objectAtIndex:i];
            int num1 = [ssqNumber.teamArray count];
            for (int j = i+1; j<[numberArray count]; ++j) {
                JddSportNumber *ssqNumber2 = [numberArray objectAtIndex:j];
                int num2 = [ssqNumber2.teamArray count];
                for (int dan1 = j+1; dan1 < [numberArray count]; ++dan1) {
                    JddSportNumber *ssqNumber3 = [numberArray objectAtIndex:dan1];
                    int num3 = [ssqNumber3.teamArray count];
                    for (int dan2 = dan1+1; dan2 < [numberArray count]; ++dan2) {
                        JddSportNumber *ssqNumber4 = [numberArray objectAtIndex:dan2];
                        int num4 = [ssqNumber4.teamArray count];
                        for (int dan3 = dan2+1; dan3 < [numberArray count]; ++dan3) {
                            JddSportNumber *ssqNumber5 = [numberArray objectAtIndex:dan3];
                            int num5 = [ssqNumber5.teamArray count];
                            for (int dan4 = dan3+1; dan4 < [numberArray count]; ++dan4) {
                                JddSportNumber *ssqNumber6 = [numberArray objectAtIndex:dan4];
                                int num6 = [ssqNumber6.teamArray count];
                                for (int dan5 = dan4+1; dan5 < [numberArray count]; ++dan5) {
                                    JddSportNumber *ssqNumber7 = [numberArray objectAtIndex:dan5];
                                    int num7 = [ssqNumber7.teamArray count];
                                    for (int dan6 = dan5+1; dan6 < [numberArray count]; ++dan6) {
                                        JddSportNumber *ssqNumber8 = [numberArray objectAtIndex:dan6];
                                        int num8 = [ssqNumber8.teamArray count];
                                        for (int dan7 = dan6+1; dan7 < [numberArray count]; ++dan7) {
                                            JddSportNumber *ssqNumber9 = [numberArray objectAtIndex:dan7];
                                            int num9 = [ssqNumber9.teamArray count];
                                            count += num1*num2*num3*num4*num5*num6*num7*num8*num9;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    countLabel.text = [NSString stringWithFormat:@"%3.0f注",count];
    moneyLabel.text = [NSString stringWithFormat:@"%3.0f彩豆",count*2*[mutiTextfield.text floatValue]];
}

-(void)numberFromArray:(NSArray *)inNumberArray{
    
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"RX9-list"];

    
    playMethodTemp = [[NSMutableArray alloc] init];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    self.titleLabel.text = [NSString stringWithFormat:@"共选择%d场,截止时间:%@",[numberArray count],endTime];
    [numberListTableView reloadData];
    
    [self caculateMoneyAndCount];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [MobClick endLogPageView:@"RX9-list"];

    if ([mutiTextfield.text length]==0) {
        mutiTextfield.text = @"1";
    }
    [mutiTextfield resignFirstResponder];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    agreeLotteryForFooterView = [JddAgreeLotteryForFooterView getInstanceView];
    agreeLotteryForFooterView.fromViewController = self;
    numberListTableView.tableFooterView = agreeLotteryForFooterView;
    [numberListTableView setSeparatorColor:SeparatorLineColor];
    if (IOS7) {
        [numberListTableView setSeparatorInset:UIEdgeInsetsZero];
    }
//        [self.navigationItem setTitle:@"任选9"];
   
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:@"任选9"];
        customLab.textAlignment = NSTextAlignmentCenter;

        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
        
        //self.navigationItem.hidesBackButton = YES;

}


- (void)viewDidUnload {
    [self setTitleLabel:nil];
    [self setCountLabel:nil];
    [self setMoneyLabel:nil];
    [self setNumberListTableView:nil];
    [self setBgScrollView:nil];
    [self setBuyBtn:nil];
    [self setMutiTextfield:nil];
    [super viewDidUnload];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)addBtnClick:(id)sender {
    NSInteger multiple = [mutiTextfield.text intValue];
    if(multiple > 99998){
        return;
    }
    mutiTextfield.text = [NSString stringWithFormat:@"%d",++multiple];
    moneyLabel.text = [NSString stringWithFormat:@"%3.0f彩豆",count*multiple*2];
}

- (IBAction)reduceBtnClick:(id)sender {
    NSInteger multiple = [mutiTextfield.text intValue];
    if(multiple-- < 2){
        return;
    }
    mutiTextfield.text = [NSString stringWithFormat:@"%d",multiple];
    moneyLabel.text = [NSString stringWithFormat:@"%3.0f彩豆",count*multiple*2];
}

- (IBAction)clearBtnClick:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"确认清空列表？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [alert show];
}

- (IBAction)buyBtnClick:(id)sender {
    int multiple = [mutiTextfield.text intValue];
    if (![JddCommonFunction isLogin]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"您还没有登录，请先登录"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:@"取消",nil ];
        [alert show];
    }  else if([numberArray count]< 9){
        [JddCommonFunction messageBoxWithMessage:@"购买内容为空，请先选择购买场次"];
    }else {
        if (!agreeLotteryForFooterView.checkBoxBtn.selected) {
            [JddCommonFunction messageBoxWithMessage:BUY_NOT_READ];
        }
        else if (multiple == 0) {
            [JddCommonFunction messageBoxWithMessage:MULTIPLE_Tip];
        }else{
            [self sureToBuy];
            /*
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"
                                                                message:@"确认购买？"
                                                               delegate:self
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:@"取消",nil ];
                [alert show];
             */
            }
    }
}

-(void)destoryView{
    playMethodTemp = [[NSMutableArray alloc] init];
    numberArray = [[NSMutableArray alloc] init];
    [mutiTextfield resignFirstResponder];
    mutiTextfield.text = @"1";
}

- (IBAction)coBuyBtnClick:(id)sender {
    if ([self checkValue]) {
    [FaQiHeMaiViewController sharedInstance].bs = [mutiTextfield.text intValue];
    [FaQiHeMaiViewController sharedInstance].lotID = LOTTERY_TYPE_ID_RX9;
    [FaQiHeMaiViewController sharedInstance].issueID = [JddPickNumRX9ViewController sharedInstance].issueID;
    [FaQiHeMaiViewController sharedInstance].issueName = [JddPickNumRX9ViewController sharedInstance].issueName;
    [FaQiHeMaiViewController sharedInstance].issueNameTitle = [NSString stringWithFormat:@"任选九第%@期合买",[JddPickNumRX9ViewController sharedInstance].issueName];
    [FaQiHeMaiViewController sharedInstance].allMoney = count * [mutiTextfield.text floatValue] * 2;
    [FaQiHeMaiViewController sharedInstance].lotteryNumber = [self lotteryNumberList];
    [[JddViewControllerManager sharedInstance].navigationController pushViewController:[FaQiHeMaiViewController sharedInstance] animated:YES];
    }
}

- (IBAction)editDidEnd:(id)sender {
    [mutiTextfield resignFirstResponder];
}

-(BOOL)checkValue{
    if ([mutiTextfield.text intValue]>99999) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"倍数不能大于99999"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil,nil ];
        [alert show];
        mutiTextfield.text =  @"99999";
        return NO;
    }else if ((count * [mutiTextfield.text floatValue] * 2) > 2000000 ){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"单个方案的总金额必须在2彩豆至2000000彩豆之间"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil,nil ];
        [alert show];
        return NO;
    }
    return YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
@end
